class Main extends egret.DisplayObjectContainer {
    private ship: Ship
    private vx: number = 0
    private vy: number = 0
    private vr: number = 0

    private thrust: number = 0
    private friction: number = 0.98

    public constructor() {
        super()
        this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this)
    }

    private onAddToStage(event: egret.Event) {
        this.stage.scaleMode = egret.StageScaleMode.NO_SCALE
        this.ship = new Ship()
        this.addChild(this.ship)
        this.ship.x = this.stage.stageWidth / 2
        this.ship.y = this.stage.stageHeight / 2
        this.stage.addEventListener(egret.TouchEvent.TOUCH_BEGIN, (evt: egret.TouchEvent) => {
            if (evt.localY < this.stage.stageHeight / 2) {
                this.thrust = 0.2
                this.ship.draw(true)
            } else {
                if (evt.localX < this.stage.stageWidth / 2) {
                    this.vr = -5
                } else {
                    this.vr = 5
                }
            }
        }, this)
        this.stage.addEventListener(egret.TouchEvent.TOUCH_END, (evt: egret.TouchEvent) => {
            this.vr = 0
            this.thrust = 0
            this.ship.draw(false)
        }, this)

        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this)
    }

    private onEnterFrame(event: egret.Event) {
        this.ship.rotation += this.vr
        let angle: number = this.ship.rotation * Math.PI / 180,
            ax: number = Math.cos(angle) * this.thrust,
            ay: number = Math.sin(angle) * this.thrust
        this.vx += ax
        this.vy += ay
        this.vx *= this.friction
        this.vy *= this.friction
        this.ship.x += this.vx
        this.ship.y += this.vy
        let left = 0
        let right = this.stage.stageWidth
        let top = 0
        let bottom = this.stage.stageHeight

        if (this.ship.x - this.ship.width / 2 > right) { // 飞船的位置 - 飞船宽度的一半 在 右边界 的 右边
            this.ship.x = left - this.ship.width / 2 // 那么飞船从左边界 - 飞船宽度一半 的 地方出现
        } else if (this.ship.x + this.ship.width / 2 < left) { // 飞船的位置 + 飞船宽度的一半 在 左边界 的 左边
            this.ship.x = right + this.ship.width / 2 // 那么飞船从右边界 + 飞船宽度一半 的 地方出现
        }

        if (this.ship.y - this.ship.height / 2 > bottom) {
            this.ship.y = top - this.ship.height / 2
        } else if (this.ship.y + this.ship.height / 2 < top) {
            this.ship.y = bottom + this.ship.height / 2
        }
    }
}